const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || "43.143.253.188",
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || "nextjs",
  password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
  database: process.env.DB_NAME || "nextjs",
  charset: 'utf8mb4',
  timezone: '+08:00',
  acquireTimeout: 60000,
  timeout: 60000,
};

// 读取基础物品JSON数据
function loadBasicItemsData() {
  try {
    const jsonPath = path.join(__dirname, 'output', '基础物品_0911.json');
    const jsonData = fs.readFileSync(jsonPath, 'utf8');
    return JSON.parse(jsonData);
  } catch (error) {
    console.error('❌ 读取基础物品JSON文件失败:', error.message);
    throw error;
  }
}

// 解析物品数据
function parseItemData(itemData) {
  const item = {
    id: itemData.id,
    name: '',
    goldPrice: 0,
    silverPrice: 0,
    lv: 1,
    weight: 1,
    description: '',
    pic: '',
    isTreasureShop: 0,
    isExpShop: 0,
    status: 1
  };

  // 解析data数组中的键值对
  itemData.data.forEach(dataItem => {
    const key = dataItem.k;
    const value = dataItem.v;

    switch (key) {
      case '名称:':
        item.name = value;
        break;
      case '价格:':
        // 解析价格，支持"50两"、"100金砖"等格式
        if (value.includes('两')) {
          item.silverPrice = parseInt(value.replace('两', '')) || 0;
        } else if (value.includes('金砖')) {
          item.goldPrice = parseInt(value.replace('金砖', '')) || 0;
        } else {
          // 默认作为银两处理
          item.silverPrice = parseInt(value) || 0;
        }
        break;
      case '等级:':
        item.lv = parseInt(value) || 1;
        break;
      case '负重:':
        item.weight = parseInt(value) || 1;
        break;
      case '介绍:':
        item.description = value;
        break;
    }
  });

  // 生成图片文件名（基于物品名称）
  item.pic = generatePicName(item.name);

  return item;
}

// 生成图片文件名
function generatePicName(itemName) {
  // 简单的图片名称生成规则，可以根据实际需要调整
  const nameMap = {
    '跌打药': 'dieda_yao',
    '止血药': 'zhixue_yao',
    '将军令': 'jiangjun_ling',
    '大将军令': 'dajiangjun_ling',
    '护身符': 'hushen_fu',
    '青铜钥匙': 'qingtong_yaoshi',
    '白银钥匙': 'baiyin_yaoshi',
    '黄金钥匙': 'huangjin_yaoshi',
    '体力丹': 'tili_dan',
    '易名神符': 'yiming_shenfu',
    '原木钥匙': 'yuanmu_yaoshi',
    '精钢钥匙': 'jinggang_yaoshi',
    '珍奇钥匙': 'zhenqi_yaoshi',
    '兵符': 'bing_fu',
    '手里剑': 'shouli_jian',
    '签到令牌': 'qiandao_lingpai',
    '壕客令牌': 'haoke_lingpai',
    '超级壕客令牌': 'chaoji_haoke_lingpai',
    '副将经验书': 'fujiang_jingyan_shu',
    '初级副将心法': 'chuji_fujiang_xinfa',
    '高级副将心法': 'gaoji_fujiang_xinfa',
    '特级副将心法': 'teji_fujiang_xinfa',
    '密宗副将心法': 'mizong_fujiang_xinfa',
    '一级技能书': 'yiji_jineng_shu',
    '二级技能书': 'erji_jineng_shu',
    '三级技能书': 'sanji_jineng_shu',
    '四级技能书': 'siji_jineng_shu',
    '五级技能书': 'wuji_jineng_shu'
  };

  return nameMap[itemName] || itemName.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '_').toLowerCase();
}

// 商店状态配置
const shopConfig = {
  // 宝物商店物品（16个）- 使用金币价格
  treasureShop: {
    '将军令': 30,
    '大将军令': 200,
    '护身符': 298,
    '青铜钥匙': 20,
    '白银钥匙': 50,
    '黄金钥匙': 100,
    '体力丹': 60,
    '易名神符': 6666,
    '原木钥匙': 50,
    '精钢钥匙': 100,
    '珍奇钥匙': 200,
    '兵符': 90,
    '手里剑': 500,
    '签到令牌': 100,
    '壕客令牌': 9999,
    '超级壕客令牌': 19999
  },

  // 经验商店物品（10个）- 使用金币价格
  expShop: {
    '副将经验书': 20,
    '初级副将心法': 40,
    '高级副将心法': 60,
    '特级副将心法': 80,
    '密宗副将心法': 100,
    '一级技能书': 20,
    '二级技能书': 40,
    '三级技能书': 60,
    '四级技能书': 80,
    '五级技能书': 100
  }
};

// 更新商店状态和价格
function updateShopStatus(item) {
  // 检查是否为宝物商店物品
  if (shopConfig.treasureShop.hasOwnProperty(item.name)) {
    item.isTreasureShop = 1;
    item.isExpShop = 0;
    // 设置金币价格，清空银币价格
    item.goldPrice = shopConfig.treasureShop[item.name];
    item.silverPrice = 0;
  }
  // 检查是否为经验商店物品
  else if (shopConfig.expShop.hasOwnProperty(item.name)) {
    item.isTreasureShop = 0;
    item.isExpShop = 1;
    // 设置金币价格，清空银币价格
    item.goldPrice = shopConfig.expShop[item.name];
    item.silverPrice = 0;
  }
  // 其他物品不上架
  else {
    item.isTreasureShop = 0;
    item.isExpShop = 0;
    // 保持原有价格设置
  }
  return item;
}

async function importBasicItems() {
  let connection;

  try {
    console.log('🚀 开始导入基础物品数据...');

    // 连接数据库
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');

    // 检查表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'basic_items'");
    if (tables.length === 0) {
      console.log('❌ basic_items 表不存在，请先创建表结构');
      return;
    }

    console.log('✅ basic_items 表存在');

    // 读取JSON数据
    console.log('📖 读取基础物品JSON数据...');
    const jsonData = loadBasicItemsData();
    const itemIds = Object.keys(jsonData);
    console.log(`📊 找到 ${itemIds.length} 个物品数据`);

    // 清空现有数据
    console.log('🗑️ 清空现有基础物品数据...');
    await connection.execute('DELETE FROM basic_items');
    console.log('✅ 现有数据已清空');

    // 导入新数据
    console.log('📥 开始导入基础物品数据...');

    const insertSql = `
      INSERT INTO basic_items (
        id, name, gold_price, silver_price, lv, weight, description, pic,
        is_treasure_shop, is_exp_shop, status, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NULL)
    `;

    let successCount = 0;
    let errorCount = 0;

    for (const itemId of itemIds) {
      try {
        const itemData = jsonData[itemId];
        let item = parseItemData(itemData);
        item = updateShopStatus(item);

        const values = [
          item.id,
          item.name,
          item.goldPrice,
          item.silverPrice,
          item.lv,
          item.weight,
          item.description,
          item.pic,
          item.isTreasureShop,
          item.isExpShop,
          item.status
        ];

        await connection.execute(insertSql, values);
        console.log(`✅ 导入物品: ${item.name} (ID: ${item.id}) - 宝物商店:${item.isTreasureShop}, 经验商店:${item.isExpShop}`);
        successCount++;

      } catch (error) {
        console.error(`❌ 导入物品失败: ID=${itemId}`, error.message);
        errorCount++;
      }
    }

    console.log('\n📊 导入结果统计:');
    console.log(`✅ 成功导入: ${successCount} 条记录`);
    console.log(`❌ 导入失败: ${errorCount} 条记录`);
    console.log(`📈 总计处理: ${itemIds.length} 条记录`);

    // 验证导入结果
    console.log('\n🔍 验证导入结果...');
    const [results] = await connection.execute('SELECT COUNT(*) as count FROM basic_items');
    console.log(`📊 数据库中现有物品数量: ${results[0].count}`);

    // 统计商店状态
    const [treasureCount] = await connection.execute('SELECT COUNT(*) as count FROM basic_items WHERE is_treasure_shop = 1');
    const [expCount] = await connection.execute('SELECT COUNT(*) as count FROM basic_items WHERE is_exp_shop = 1');
    const [bothCount] = await connection.execute('SELECT COUNT(*) as count FROM basic_items WHERE is_treasure_shop = 1 AND is_exp_shop = 1');
    const [noneCount] = await connection.execute('SELECT COUNT(*) as count FROM basic_items WHERE is_treasure_shop = 0 AND is_exp_shop = 0');

    console.log('\n📈 商店状态统计:');
    console.log(`🏪 宝物商店: ${treasureCount[0].count} 个物品`);
    console.log(`📚 经验商店: ${expCount[0].count} 个物品`);
    console.log(`🔄 两个商店都有: ${bothCount[0].count} 个物品`);
    console.log(`❌ 未上架: ${noneCount[0].count} 个物品`);

    // 显示商店物品列表
    console.log('\n🏪 宝物商店物品列表:');
    const [treasureItems] = await connection.execute(`
      SELECT id, name, silver_price, gold_price 
      FROM basic_items
      WHERE is_treasure_shop = 1 
      ORDER BY gold_price DESC, silver_price DESC
    `);
    treasureItems.forEach(item => {
      const price = item.gold_price > 0 ? `${item.gold_price}金币` : `${item.silver_price}银币`;
      console.log(`  ${item.id}. ${item.name} - ${price}`);
    });

    console.log('\n📚 经验商店物品列表:');
    const [expItems] = await connection.execute(`
      SELECT id, name, silver_price, gold_price 
      FROM basic_items
      WHERE is_exp_shop = 1 
      ORDER BY gold_price DESC, silver_price DESC
    `);
    expItems.forEach(item => {
      const price = item.gold_price > 0 ? `${item.gold_price}金币` : `${item.silver_price}银币`;
      console.log(`  ${item.id}. ${item.name} - ${price}`);
    });

    console.log('\n🎉 基础物品数据导入完成！');

  } catch (error) {
    console.error('❌ 导入过程中发生错误:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行导入
if (require.main === module) {
  importBasicItems()
    .then(() => {
      console.log('✅ 脚本执行完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = { importBasicItems, parseItemData, updateShopStatus };